# -*- coding:utf-8 -*-

from PyQt5 import QtGui, QtCore, Qt
from PyQt5.QtCore import Qt, QUrl,QCoreApplication
from PyQt5.QtGui import QPixmap, QIcon,QTextDocument,QTextCursor
from PyQt5.QtWidgets import QApplication, QMainWindow, QDialog, QDialogButtonBox, QVBoxLayout, QLabel, QAction, \
    QTextEdit, QPushButton, QMessageBox,QWidget,QDesktopWidget
from PyQt5.QtWebEngineWidgets import QWebEngineView,QWebEnginePage
import os,platform
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from bzmodel.model import Base,Bwpubparm
from bzprinter.printer import Printer,test_html
from PyQt5.QtPrintSupport import QPrinterInfo,QPrinter,QPrintPreviewDialog
from bzprinter.bzprintshareobj import ActiveXExtend
from PyQt5.QtOpenGL import QGLWidget
import os


"""
博智WEB 类文件
"""

"""
多线程应用类
"""
class ApplicationThread(QtCore.QThread):
    def __init__(self, application, port=5000):
        super(ApplicationThread, self).__init__()
        self.application = application
        self.port = port

    def __del__(self):
        self.wait()

    def run(self):
        self.application.run(port=self.port, threaded=True)


class WebPage(QWebEnginePage):
    def __init__(self, root_url):
        super(WebPage, self).__init__()
        self.root_url = root_url

    def home(self):
        self.load(QtCore.QUrl(self.root_url))

    def acceptNavigationRequest(self, url, kind, is_main_frame):
        """Open external links in browser and internal links in the webview"""
        ready_url = url.toEncoded().data().decode()
        is_clicked = kind == self.NavigationTypeLinkClicked
        if is_clicked and self.root_url not in ready_url:
            QtGui.QDesktopServices.openUrl(url)
            return False
        return super(WebPage, self).acceptNavigationRequest(url, kind, is_main_frame)


# 数据库
class Conndb:
    def __init__(self):
        engine = create_engine('sqlite:///' + os.path.join('db','bzweb.db'))
        Base.metadata.create_all(engine)
        DbSession = sessionmaker(engine)
        self.session = DbSession()

# 关于窗体
class AboutDialog(QDialog):
    def __init__(self, *args, **kwargs):
        super(AboutDialog, self).__init__(*args, **kwargs)

        QBtn = QDialogButtonBox.Ok  # No cancel
        self.buttonBox = QDialogButtonBox(QBtn)
        self.buttonBox.accepted.connect(self.accept)
        self.buttonBox.rejected.connect(self.reject)

        layout = QVBoxLayout()

        title = QLabel("博智软件")
        font = title.font()
        font.setPointSize(20)
        title.setFont(font)

        layout.addWidget(title)

        logo = QLabel()
        logo.setPixmap(QPixmap(os.path.join('images', 'ma-icon-128.png')))
        layout.addWidget(logo)

        layout.addWidget(QLabel("Version V1.2"))
        layout.addWidget(QLabel("Copyright 2025 博智科技 TEL 13973343798"))

        for i in range(0, layout.count()):
            layout.itemAt(i).setAlignment(Qt.AlignCenter)

        layout.addWidget(self.buttonBox)

        self.setLayout(layout)

# 系统地址窗口
class UrlDlg(QDialog):
    def __init__(self,parent=None):
        super(UrlDlg, self).__init__(parent)
        self.setWindowTitle('系统登录地址')
        self.resize(400,300)

        self.url_text = QTextEdit()
        self.btnSave = QPushButton('保存')
        self.btnClose = QPushButton('关闭')

        try:
            conndb = Conndb()
            session = conndb.session
            pparm = session.query(Bwpubparm).filter(Bwpubparm.ppid == 'sys_url').first()
            if pparm is not None:
                self.url_text.setText(pparm.ppvalue)
            else:
                self.url_text.setPlaceholderText('请输入登录 URL')
            session.close()
        except Exception as e:
            QMessageBox.critical(self, '系统错误', '查询失败,请联系 13973343798 言工', QMessageBox.Yes, QMessageBox.Yes)

        layout = QVBoxLayout()
        layout.addWidget(self.url_text)
        layout.addWidget(self.btnSave)
        self.btnSave.clicked.connect(self.btnSave_clicked)
        layout.addWidget(self.btnClose)
        self.btnClose.clicked.connect(self.btnClose_clicked)
        self.setLayout(layout)

    # 保存系统url
    def btnSave_clicked(self):
        url_text = self.url_text.toPlainText()
        if url_text is None:
            QMessageBox.warning(self, '系统提示', '请输入正确的 URL 地址',QMessageBox.Yes,QMessageBox.Yes)
            return False
        try:
            conndb = Conndb()
            session = conndb.session
            pparms = session.query(Bwpubparm).filter(Bwpubparm.ppid == 'sys_url').all()
            if len(pparms):
                pparm = session.query(Bwpubparm).filter(Bwpubparm.ppid == 'sys_url').first()
                pparm.ppvalue = url_text
                pparm.memo = '修改'
            else:
                pparm = Bwpubparm(ppid='sys_url', ppname='系统应用地址', ppvalue=url_text,
                                  memo='新增')
                session.add(pparm)
            session.commit()
            session.close()
            QMessageBox.about(self,'系统提示','应用地址保存成功,请重新启动系统!')
        except Exception as e:
            QMessageBox.critical(self, '系统错误', '保存失败,请联系 13973343798 言工', QMessageBox.Yes, QMessageBox.Yes)

    def btnClose_clicked(self):
        self.close()


# 打印设置窗口
class PrintsetDlg(QDialog):
    def __init__(self):
        pass



"""
主窗体
"""
class Bzmainwindow(QMainWindow):
    def __init__(self, *args, **kwargs):
        super(Bzmainwindow, self).__init__(*args, **kwargs)

        desktop = QApplication.desktop()
        self.setGeometry(desktop.availableGeometry())
        # self.setGeometry(10,10,1024,768)
        self.showMaximized()
        self.setWindowTitle('博智WebApp 博汇顾客 智慧决策')
        self.setWindowIcon(QtGui.QIcon('start.ico'))

        # WebView层
        self.webView = QWebEngineView(self)
        self.setCentralWidget(self.webView)

        # WebPage层
        url = ''
        try:
            conndb = Conndb()
            session = conndb.session
            pparm = session.query(Bwpubparm).filter(Bwpubparm.ppid == 'sys_url').first()
            if pparm is not None and len(pparm.ppvalue) > 10:
                url = pparm.ppvalue
            else:
                url = 'http://www.zzbozhi.net'
            session.close()
        except Exception as e:
            url = 'http://www.zzbozhi.net'
            QMessageBox.critical(self,'系统错误','严重错误,请联系开发商 13973343798 言工',QMessageBox.Yes,QMessageBox.Yes)

        self.page = WebPage(url)
        self.page.home()
        self.webView.setPage(self.page)

        bz_menu_setup = self.menuBar().addMenu("& 设置")
        url_action = QAction(QIcon(os.path.join('images', 'home.png')), "系统地址", self)
        url_action.triggered.connect(self.url_set)
        bz_menu_setup.addAction(url_action)

        # print_action = QAction(QIcon(os.path.join('images', 'question.png')), "打印参数", self)
        # print_action.triggered.connect(self.print_set)
        # bz_menu_setup.addAction(print_action)

        print_test_action = QAction(QIcon(os.path.join('images', 'printer.png')), "打印测试", self)
        print_test_action.triggered.connect(self.print_test)
        bz_menu_setup.addAction(print_test_action)

        bz_menu_help = self.menuBar().addMenu("&H 帮助")
        about_action = QAction(QIcon(os.path.join('images', 'about.png')), "关于博智", self)
        # about_action.setStatusTip("博智软件 TEL:13973343798")
        about_action.triggered.connect(self.about)
        bz_menu_help.addAction(about_action)

        close_action = QAction(QIcon(os.path.join('images', 'exit.png')), "退出系统", self)
        close_action.triggered.connect(self.sys_close)
        bz_menu_help.addAction(close_action)


    # 系统地址
    def url_set(self):
        dlg = UrlDlg()
        dlg.exec()

    # 打印设置
    def print_set(self):
        pass

    # 打印测试页
    def print_test(self):
        sysstr = platform.system()
        if sysstr == 'Windows':
            try:
                act = ActiveXExtend(None)
                act.ocx.PRINT_INIT('博智打印')
                act.ocx.ADD_PRINT_TABLE(6, 20, 770, 1000, test_html)
                act.ocx.PREVIEW()
            except Exception as e:
                QMessageBox.critical(self, '系统错误', '调用打印组件加载异常，请联系开发商 13973343798 言工', QMessageBox.Yes,
                                     QMessageBox.Yes)

        else:
            QMessageBox.critical(self, '系统错误', '没有' + str(sysstr) + '打印驱动 请咨询13973343798 言工', QMessageBox.Yes,
                                 QMessageBox.Yes)

    # 执行测试打印
    def printHtml(self,printer):
        textDocument = QTextDocument()
        textDocument.setHtml(test_html)
        textDocument.print_(printer)

    # 关于
    def about(self):
        dlg = AboutDialog()
        dlg.exec()

    # 关闭系统
    def sys_close(self):
        reply = QMessageBox.question(self,'系统提示','请确定数据保存了后再退出系统?',
                                     QMessageBox.Yes | QMessageBox.No,
                                     QMessageBox.No)
        if(reply == QMessageBox.Yes):
            os.remove("execute.pkl")
            QCoreApplication.instance().quit()
            # self.close()

    def closeEvent(self,event):
        os.remove("execute.pkl")
        #print(os.getcwd())
        # reply = QMessageBox(self,'系统提示','请确定数据保存了后再退出系统1?',
        #                              QMessageBox.Yes | QMessageBox.No,
        #                              QMessageBox.No)
        # if reply == QMessageBox.Yes:
        #    event.accept()
        # else:
        #     event.ignore()


# 解决OPENGL 动态库引入问题
class OpenGLWidget(QGLWidget):
    def __init__(self):
        pass



